
/**    
 * @Title: FileController.java  
 * @Package cn.com.thinvent.redcross.volunteer.web.controller  
 * @Description: TODO  
 * @author liuxg  
 * @date 2017年8月22日  
 * @version V1.0    
 */

package io.gbznt.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

import io.gbznt.common.utils.FileConfigReader;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.modules.sys.entity.SysFiletableEntity;
import io.gbznt.modules.sys.fileentity.CommConstants;
import io.gbznt.modules.sys.fileentity.FileUtil;
import io.gbznt.modules.sys.fileentity.UploadMessage;
import io.gbznt.modules.sys.service.SysFiletableService;

/**
 * @ClassName: FileController
 * @Description: 这是一个专门用来处理上传文件和下载文件的控制器
 * @author xucg
 * @date 2017年8月22日
 * 
 */
@RestController
@RequestMapping(value = "/fileAction")
public class FileController {
	@Autowired
	private SysFiletableService sysFiletableService;

	@RequestMapping(value = "/uploadFile")
	@ResponseBody
	public UploadMessage getUploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
									   HttpServletRequest request) {
		UploadMessage uploadFile = FileUtil.uploadFile(file);
		return uploadFile;
	}

	/**
	 * 上传文件 返回path
	 * @param filep
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "uploadFile2")
	@ResponseBody
	public R getUploadFile2(@RequestParam(value = "imgFile") MultipartFile filep, HttpServletRequest request,
							HttpServletResponse response) throws IOException {
		System.out.println("文件的上传的控制器........................................");

		// 图片名称添加时间轴
		String imagehz = filep.getOriginalFilename().substring(filep.getOriginalFilename().lastIndexOf("."));
		String name = "upfile_" + System.currentTimeMillis() + "_" + imagehz;

		long size = filep.getSize();
		String ms = FileConfigReader.getUploadFileMaxSize();
		if (ms != null && size > Long.parseLong(ms)) {
			return R.error("上传的文件过大");
		}

		/**
		 * 开始将这个文件或者图片上传的服务器中的某个磁盘中
		 */
		String rootPath = FileConfigReader.getUploadFilePath();
		// 判断当前系统是window还是linux
		/*
		 * if (System.getProperty(CommConstants.OS_FLAG_STR).toLowerCase().startsWith(
		 * CommConstants.OS_WIN_STR)) { //获取系统视图资源 FileSystemView sys =
		 * FileSystemView.getFileSystemView(); //获取计算机驱动资源 File[] filesQ =
		 * File.listRoots(); File cFile = new File(CommConstants.OS_WIN_C_PATH_STR);
		 * for(File t:filesQ){ if(t != null && !t.equals(cFile)){
		 * if(sys.getSystemTypeDescription(t).equals(CommConstants.OS_WIN_PATH_VALUE_STR
		 * )){//是否为本地磁盘 //rootPath = rootPath; break; } } } } else { rootPath =
		 * CommConstants.OS_NOT_WIN_PATH_STR; }
		 */

		String path = rootPath + File.separator + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		StringBuffer sbuf = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			sbuf.append(random.nextInt(10));
		}
		String fileName = sbuf.append("_").append(name).toString();

		File insertFile = new File(path, fileName);
		if (!insertFile.getParentFile().exists()) {
			insertFile.getParentFile().mkdirs();
		}
		try {
			filep.transferTo(insertFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return R.error();
		} catch (IOException e) {
			e.printStackTrace();
			return R.error();
		}

		String savepath = URLEncoder.encode(insertFile.getAbsolutePath(), "utf-8");
		return R.ok().put("path",savepath).
				put("url", request.getContextPath() + "/fileAction/loadImg?cateogry=" + savepath);
	}

	/**
	 * 上传文件 并存入文件表  返回path id
	 * @param filep
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "uploadFile3")
	@ResponseBody
	public R webuploadfile(@RequestParam(value = "file") MultipartFile filep, HttpServletRequest request,
                              HttpServletResponse response) throws IOException {

		System.out.println("文件的上传的控制器........................................");

		// 图片名称添加时间轴
		String imagehz = filep.getOriginalFilename().substring(filep.getOriginalFilename().lastIndexOf("."));
		String name = "upfile_" + System.currentTimeMillis() + "_" + imagehz;

		long size = filep.getSize();
		String ms = FileConfigReader.getUploadFileMaxSize();
		if (ms != null && size > Long.parseLong(ms)) {
			return R.error("上传的文件过大");
		}

		/**
		 * 开始将这个文件或者图片上传的服务器中的某个磁盘中
		 */
		String rootPath = FileConfigReader.getUploadFilePath();

		String path = rootPath + File.separator + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		StringBuffer sbuf = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			sbuf.append(random.nextInt(10));
		}
		String fileName = sbuf.append("_").append(name).toString();

		File insertFile = new File(path, fileName);
		if (!insertFile.getParentFile().exists()) {
			insertFile.getParentFile().mkdirs();
		}

		try {
			filep.transferTo(insertFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return R.error("文件存储异常");
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("文件存储异常");
		}

		String savepath = URLEncoder.encode(insertFile.getAbsolutePath(), "utf-8");

		//备注
		String mark = request.getParameter("mark");

		// 上传成功执行 新增文件表操作
		SysFiletableEntity sysFiletable = new SysFiletableEntity();
		sysFiletable.setFileName(fileName);
		sysFiletable.setFileType(imagehz);
		sysFiletable.setCreateId(ShiroUtils.getUserId()+"");
		sysFiletable.setFileUrl(savepath);
		sysFiletable.setFileRemark(mark);
		sysFiletable.setCreateTime(new Date());
		sysFiletable.setCreateId(ShiroUtils.getUserId());
		sysFiletable.setCreateName(ShiroUtils.getUserName());
		sysFiletable.setFileRealname(filep.getOriginalFilename());

		sysFiletableService.save(sysFiletable);

		R r = R.ok();
		r.put("fileId", sysFiletable.getId());
		r.put("path", savepath);
		r.put("url", request.getContextPath() + "/fileAction/loadImg?cateogry=" + savepath);
		return r;
	}


	@RequestMapping(value = "loadImg")
	@ResponseBody
	public void loadImg(HttpServletResponse response, String cateogry) throws IOException {
		System.out.println("读取图片----");
		if (cateogry.indexOf(",") >= 0) {
			cateogry = cateogry.replace(",", "");
		}
		if (io.netty.util.internal.StringUtil.isNullOrEmpty(cateogry)) {
			cateogry = this.getClass().getClassLoader().getResource("statics").getPath() + "/images/default.png";
		}
		cateogry = URLDecoder.decode(cateogry);
		File file = new File(cateogry);
		// FileConfigReader.getProperties("rootPath")+File.separator+filePath;*/
		/*
		 * File file = new File(PropertyUtils.getPropertyValueByKey(
		 * "configure.properties", "headImgPath")+"/"+cateogry);
		 */

		if (!file.exists()) {
			cateogry = this.getClass().getClassLoader().getResource("statics").getPath() + "/images/default.png";
			file = new File(cateogry);
		}
		FileInputStream inputStream = new FileInputStream(file);
		byte[] data = new byte[(int) file.length()];
		inputStream.read(data);
		inputStream.close();

		String fileType = cateogry.substring(cateogry.indexOf(".") + 1, cateogry.length());
		if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"pdf".equals(fileType) && !"png".equals(fileType)) {
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String((new Date().toLocaleString() + "." + fileType).getBytes("GBK"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(file.length()));
			// response.setContentType("application/octet-stream");
		}

		OutputStream stream = response.getOutputStream();
		stream.write(data);
		stream.flush();
		stream.close();
	}

	private String createRootPath() {
		String path = CommConstants.OS_WIN_C_PATH_STR + CommConstants.OS_WIN_PATH_STR;
		// 判断当前系统是window还是linux
		/*
		 * if (System.getProperty(CommConstants.OS_FLAG_STR).toLowerCase().startsWith(
		 * CommConstants.OS_WIN_STR)) { //获取系统视图资源 FileSystemView sys =
		 * FileSystemView.getFileSystemView(); //获取计算机驱动资源 File[] filesQ =
		 * File.listRoots(); File cFile = new File(CommConstants.OS_WIN_C_PATH_STR);
		 * for(File t:filesQ){ if(t != null && !t.equals(cFile)){
		 * if(sys.getSystemTypeDescription(t).equals(CommConstants.OS_WIN_PATH_VALUE_STR
		 * )){//是否为本地磁盘 path = t + CommConstants.OS_WIN_PATH_STR; break; } } } } else {
		 * path = CommConstants.OS_NOT_WIN_PATH_STR; }
		 */
		return path;
	}

	/**
	 * 根据二进制表的Id来获取这个这个二进制表中的图片或者文件,以IO流的形式将这个图片或者文件写回去
	 * 
	 * @param resp
	 * @param req
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "downloadFile")
	public void downloadFile(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		req.setCharacterEncoding("utf-8");

		String bytearrayId = req.getParameter("bytearrayId");
		// 若有多图 只读最后一章
		if (bytearrayId.indexOf(",") >= 0) {
			bytearrayId = bytearrayId.substring(0, bytearrayId.length() - 1);
			int one = bytearrayId.lastIndexOf(",");
			bytearrayId = bytearrayId.substring((one + 1), bytearrayId.length());
		}

		SysFiletableEntity sysFiletable = new SysFiletableEntity();

		try {
			sysFiletable = sysFiletableService.getById(bytearrayId);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//
		String url = "";
		String name = "";
		if (sysFiletable == null) {
			name = "default.png";
			url = this.getClass().getClassLoader().getResource("statics").getPath() + "/images/default.png";
		} else {
			url = sysFiletable.getFileUrl();
			if (sysFiletable.getFileRealname() != null) {
				name = sysFiletable.getFileRealname();
			} else {
				name = sysFiletable.getFileName();
			}

		}
		url = URLDecoder.decode(url, "utf-8");
		System.out.println("文件或者图片在服务器磁盘中的地址 : " + url + "文件或者图片在服务器磁盘中的名字  : " + name);
		try {
			if (name != null && !"".equals(name)) {
				// 文件路径
				File file = new File(url);
				if (!file.exists()) {
					name = "default.png";
					url = this.getClass().getClassLoader().getResource("statics").getPath() + "/images/default.png";
					file = new File(url);
				}

				if (file.exists()) {
					resp.setContentType("text/html;charset=utf-8");
					String fileType = name.substring(name.indexOf(".") + 1, name.length());
					System.out.println(fileType);
					if ("jpg".equals(fileType) || "jpeg".equals(fileType) || "png".equals(fileType)) {
						resp.setContentType("image/*");
					} else {
						resp.setContentType("application/octet-stream");
					}
					// 适配多浏览器
					resp.setHeader("Content-disposition",
							"attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859-1"));
					resp.setHeader("Content-Length", String.valueOf(file.length()));
					// 设置缓存
					inputStream = new BufferedInputStream(new FileInputStream(file));
					outputStream = new BufferedOutputStream(resp.getOutputStream());
					byte[] buff = new byte[(int) file.length()];
					int bytesRead;
					while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))) {
						outputStream.write(buff, 0, bytesRead);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 首页专用 xcg 根据二进制表的Id来获取这个这个二进制表中的图片或者文件,以IO流的形式将这个图片或者文件写回去
	 * 
	 * @param resp
	 * @param req
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "downloadFileindex")
	public void downloadFileindex(HttpServletResponse resp, HttpServletRequest req)
			throws ServletException, IOException {
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		req.setCharacterEncoding("utf-8");

		String bytearrayId = req.getParameter("bytearrayId");
		// 若有多图 只读最后一章
		if (bytearrayId.indexOf(",") >= 0) {
			bytearrayId = bytearrayId.substring(0, bytearrayId.length() - 1);
			int one = bytearrayId.lastIndexOf(",");
			bytearrayId = bytearrayId.substring((one + 1), bytearrayId.length());
		}

		SysFiletableEntity sysFiletable = new SysFiletableEntity();

		try {
			sysFiletable = sysFiletableService.getById(bytearrayId);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//
		String url = "";
		String name = "";
		if (sysFiletable == null) {
			name = "default.png";
			// url =
			// this.getClass().getClassLoader().getResource("statics").getPath()+"/images/default.png";
		} else {
			url = sysFiletable.getFileUrl();
			if (sysFiletable.getFileRealname() != null) {
				name = sysFiletable.getFileRealname();
			} else {
				name = sysFiletable.getFileName();
			}

		}
		url = URLDecoder.decode(url, "utf-8");
		System.out.println("文件或者图片在服务器磁盘中的地址 : " + url + "文件或者图片在服务器磁盘中的名字  : " + name);
		try {
			if (name != null && !"".equals(name)) {
				// 文件路径
				File file = new File(url);
				if (!file.exists()) {
					name = "default.png";
					// url =
					// this.getClass().getClassLoader().getResource("statics").getPath()+"/images/default.png";
					file = new File(url);
				}

				if (file.exists()) {
					resp.setContentType("text/html;charset=utf-8");
					String fileType = name.substring(name.indexOf(".") + 1, name.length());
					System.out.println(fileType);
					if ("jpg".equals(fileType) || "jpeg".equals(fileType) || "png".equals(fileType)) {
						resp.setContentType("image/*");
					} else {
						resp.setContentType("application/octet-stream");
					}
					// 适配多浏览器
					resp.setHeader("Content-disposition",
							"attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859-1"));
					resp.setHeader("Content-Length", String.valueOf(file.length()));
					// 设置缓存
					inputStream = new BufferedInputStream(new FileInputStream(file));
					outputStream = new BufferedOutputStream(resp.getOutputStream());
					byte[] buff = new byte[(int) file.length()];
					int bytesRead;
					while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))) {
						outputStream.write(buff, 0, bytesRead);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * @Description: 加载附件
	 * @author : 郭强 guoqiang@qq.com
	 * @date : 2017年11月22日 下午2:24:41
	 * @param response
	 * @param bytearrayId
	 * @throws IOException
	 */
	@RequestMapping("loadFile")
	public void loadFile(HttpServletResponse response, String bytearrayId) throws IOException {

		SysFiletableEntity sysFiletable = sysFiletableService.getById(bytearrayId);

		String name = "";
		String url = sysFiletable.getFileUrl();
		url = URLDecoder.decode(url, "utf-8");
		File file = new File(url);

		FileInputStream inputStream = new FileInputStream(file);
		byte[] data = new byte[(int) file.length()];
		inputStream.read(data);
		inputStream.close();

		if (sysFiletable.getFileRealname() != null) {
			name = sysFiletable.getFileRealname();
		} else {
			name = sysFiletable.getFileName();
		}
		String fileType = name.substring(name.indexOf(".") + 1, name.length());
		// if("jpg".equals(fileType)||
		// "jpeg".equals(fileType)){
		// response.setContentType("image/*");
		// response.setContentType("image/png");
		// }else{
		// response.setContentType("application/octet-stream");
		// }
		// response.setHeader("Content-disposition", "attachment; filename=" + new
		// String(name.getBytes("GBK"),"ISO8859-1"));
		// response.setHeader("Content-Length", String.valueOf(file.length()));
		OutputStream stream = response.getOutputStream();
		stream.write(data);
		stream.flush();
		stream.close();
	}

	/*
	 * @RequestMapping(value="updateFile") public void
	 * updateFile(HttpServletResponse resp,HttpServletRequest req) throws
	 * ServletException, IOException{ BufferedInputStream inputStream= null;
	 * BufferedOutputStream outputStream= null; req.setCharacterEncoding("utf-8");
	 * 
	 * String bytearrayId = req.getParameter("bytearrayId");
	 * 
	 * 
	 * Bytearray baseInfo = commonService.getFileBaseInfo(bytearrayId);
	 * 
	 * String url = baseInfo.getUrl(); String name = baseInfo.getName();
	 * 
	 * System.out.println("文件或者图片在服务器磁盘中的地址 : "+url+"文件或者图片在服务器磁盘中的名字  : "+name);
	 * try { if(name!=null && !name.equals("")){ // 文件路径 File file = new File(url);
	 * if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } if
	 * (file.exists()) { resp.setContentType("text/html;charset=utf-8"); String
	 * fileType = name.substring(name.indexOf(".")+1,name.length());
	 * System.out.println(fileType); if("jpg".equals(fileType)||
	 * "jpeg".equals(fileType)){ resp.setContentType("image/*"); }else{
	 * resp.setContentType("application/octet-stream;"); } // 适配多浏览器
	 * resp.setHeader("Content-disposition", "attachment; filename=" + new
	 * String(name.getBytes("GBK"),"ISO8859-1")); resp.setHeader("Content-Length",
	 * String.valueOf(file.length())); // 设置缓存 inputStream= new
	 * BufferedInputStream(new FileInputStream(file)); outputStream= new
	 * BufferedOutputStream(resp.getOutputStream()); byte[] buff = new byte[2048];
	 * int bytesRead; while (-1 != (bytesRead = inputStream.read(buff, 0,
	 * buff.length))) { outputStream.write(buff, 0, bytesRead); } } } } catch
	 * (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) try
	 * { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } if
	 * (outputStream != null) try { outputStream.close(); } catch (IOException e) {
	 * e.printStackTrace(); } } }
	 */

	@RequestMapping(value = "showImage")
	public void showImage(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		req.setCharacterEncoding("utf-8");
		String filePath = req.getParameter("filePath");
		String fileName = req.getParameter("fileName");
		System.out.println("文件保存在服务器磁盘中的地址 : " + filePath + "文件保存在服务器磁盘中的名字  : " + fileName);
		try {
			if (filePath != null && !"".equals(filePath) && fileName != null && !"".equals(fileName)) {
				// 文件路径
				String path = FileConfigReader.getProperties("rootPath") + File.separator + filePath;
				File file = new File(path, fileName);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				if (file.exists()) {
					resp.setContentType("text/html;charset=utf-8");
					String fileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
					System.out.println(fileType);
					if ("jpg".equals(fileType) || "jpeg".equals(fileType)) {
						resp.setContentType("image/*");
					} else {
						resp.setContentType("application/octet-stream;");
					}
					// 适配多浏览器
					resp.setHeader("Content-disposition",
							"attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
					resp.setHeader("Content-Length", String.valueOf(file.length()));
					// 设置缓存
					inputStream = new BufferedInputStream(new FileInputStream(file));
					outputStream = new BufferedOutputStream(resp.getOutputStream());
					byte[] buff = new byte[2048];
					int bytesRead;
					while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))) {
						outputStream.write(buff, 0, bytesRead);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}



	// 读取图片
	/*
	 * public void loadImg(HttpServletResponse response, String cateogry) throws
	 * IOException {
	 * 
	 * if(io.netty.util.internal.StringUtil.isNullOrEmpty(cateogry)) { cateogry =
	 * "default.png"; }
	 * 
	 * File file = new File(PropertyUtils.getPropertyValueByKey(
	 * "configure.properties", "headImgPath")+"/"+cateogry);
	 * 
	 * FileInputStream inputStream = new FileInputStream(file); byte[] data = new
	 * byte[(int)file.length()]; inputStream.read(data); inputStream.close();
	 * 
	 * response.setContentType("image/png");
	 * 
	 * OutputStream stream = response.getOutputStream(); stream.write(data);
	 * stream.flush(); stream.close(); }
	 */

	public JSONObject getConfig() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("imageActionName", "uploadimage"); // 执行上传图片的action名称
		jsonObject.put("imageAllowFiles", new String[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp" }); // 允许上传的图片类型
		jsonObject.put("imageFieldName", "upfile"); // 提交的图片表单名称
		jsonObject.put("imageMaxSize", "2048000"); // 上传大小限制，机构B
		jsonObject.put("imageCompressEnable", true); // 是否压缩图片,默认是true
		jsonObject.put("imageCompressBorder", 1600); // 图片压缩最长边限制
		jsonObject.put("imageInsertAlign", "none"); // 插入的图片浮动方式
		jsonObject.put("imageUrlPrefix", "http://xinrui.com/image/"); // 图片访问路径前缀
		jsonObject.put("imagePathFormat", "/{yyyy}{mm}{dd}/{time}{rand:6}"); // 上传保存路径,可以自定义保存路径和文件名格式
		return jsonObject;
	}

	/**
	 * 判断文件是否是图片
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private static boolean isImage(File file) throws IOException {
		BufferedImage bi = ImageIO.read(file);
		if (bi == null) {
			return false;
		}
		return true;
	}

	/**
	 * 下载word模板
	 * 
	 * @param resp
	 * @param req
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "downword")
	public void downword(HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
		// 下载模板选择
		String type = req.getParameter("type");
		String url = "";
		if (("xfj").equals(type)) {
			// 信访件
			url = "/docmodule/Scvisit.docx";
		} else if (("xssl").equals(type)) {
			// 线索受理
			url = "/docmodule/Scvisitxs.docx";
		}

		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		req.setCharacterEncoding("utf-8");

		// String bytearrayId = req.getParameter("bytearrayId");

		// SysFiletableEntity sysFiletable = new SysFiletableEntity();

		try {
			// sysFiletable = sysFiletableService.selectById(bytearrayId);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//

		String name = "Scvisit.docx";
		/*
		 * if(sysFiletable == null){
		 * 
		 * }else{ url = sysFiletable.getFileUrl(); name = sysFiletable.getFileName(); }
		 */
		url = URLDecoder.decode(url, "utf-8");
		System.out.println("文件或者图片在服务器磁盘中的地址 : " + url + "文件或者图片在服务器磁盘中的名字  : " + name);
		try {
			if (name != null && !"".equals(name)) {
				// 文件路径
				File file = new File(this.getClass().getClassLoader().getResource("statics").getPath() + url);
				System.out.println("文件路径--" + this.getClass().getClassLoader().getResource("statics").getPath());
				System.out.println(file.getAbsolutePath());
				if (!file.getParentFile().exists()) {
					// file.getParentFile().mkdirs();
				}
				if (file.exists()) {
					resp.setContentType("text/html;charset=utf-8");
					String fileType = name.substring(name.indexOf(".") + 1, name.length());
					System.out.println(fileType);
					if ("jpg".equals(fileType) || "jpeg".equals(fileType)) {
						resp.setContentType("image/*");
					} else {
						resp.setContentType("application/octet-stream");
					}
					// 适配多浏览器
					resp.setHeader("Content-disposition",
							"attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859-1"));
					resp.setHeader("Content-Length", String.valueOf(file.length()));
					// 设置缓存
					inputStream = new BufferedInputStream(new FileInputStream(file));
					outputStream = new BufferedOutputStream(resp.getOutputStream());
					byte[] buff = new byte[2048];
					int bytesRead;
					while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))) {
						outputStream.write(buff, 0, bytesRead);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 根据路径的下载方法
	 * 
	 * @param response
	 * @param request
	 * @param filepath
	 */
	@RequestMapping("/downloadFileByPath")
	public void downloadFileByPath(HttpServletResponse response, HttpServletRequest request, String filepath) {
		if (StringUtils.isNotEmpty(filepath)) {
			// 文件路径
			File file = new File(filepath);
			if (!file.exists()) {
				filepath = this.getClass().getClassLoader().getResource("statics").getPath() + "/images/default.png";
				file = new File(filepath);
				System.out.println("未找到文件");
			}
			System.out.println("文件路径--" + filepath);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + file.getName());// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
	@RequestMapping("/uploadhf")
	public R uploadhf( HttpServletRequest request) {
	 
	    CommonsMultipartResolver cmr = new CommonsMultipartResolver(
	            request.getServletContext());
	    if (cmr.isMultipart(request)) {
	        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
	        Iterator<String> files = mRequest.getFileNames();
	        String imgPath = "";
	        String ids = "";
	        while (files.hasNext()) {
	            MultipartFile mFile = mRequest.getFile(files.next());
	            if (mFile != null) {
	            	try {
	            		String fileName = UUID.randomUUID() + mFile.getOriginalFilename();
		                Map<String, Object> nm = new HashMap<>();
		              //  nm.get("")
		                nm = saveFile(mFile,request);
		                
		                //imgPath += nm.get("id") +";";
		                ids += nm.get("id") +",";
		                
		              
					} catch (Exception e) {
						// TODO: handle exception
						return R.error();
					}
	                
	                
	            }
	        }
	        if(ids.length()>0){
	        	ids = ids.substring(0, ids.length()-1);
	        }
	        return R.ok().put("id", ids);
	    }
	 
	    return R.ok();
	}
	private Map<String,Object> saveFile(MultipartFile file, HttpServletRequest request){
	    String path= "";
	    Map<String, Object> nm = new HashMap<>();
	    try {
	        byte[] bytes = file.getBytes();
	 
	        // 当前app根目录
	        String rootPath = request.getServletContext().getRealPath("/");
	 
	        // 需要上传的相对地址（application.properties中获取）
	        //String relativePath = env.getProperty("image.file.upload.dir");
	        String relativePath = FileConfigReader.getUploadFilePath();
	 
	        // 文件夹是否存在，不存在就创建
	        File dir = new File(relativePath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
	        if (!dir.exists())
	            dir.mkdirs();
	       // String fileExtension = getFileExtension(file);
	 
	        String imagehz = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
	        
	        // 生成UUID样式的文件名
	        String filename = java.util.UUID.randomUUID().toString() + "." + imagehz;
	 
	        // 文件全名
	        String fullFilename = dir.getAbsolutePath() + File.separator + filename;
	 
	        // 被访问路径
	        String relativeFile = relativePath + filename;
	 
	        // 保存图片
	        File serverFile = new File(fullFilename);
	        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
	        stream.write(bytes);
	        stream.close();
	        
	     // 上传成功执行 新增文件表操作
	        String savepath = URLEncoder.encode(serverFile.getAbsolutePath(), "utf-8");
			SysFiletableEntity sysFiletable = new SysFiletableEntity();
			sysFiletable.setFileName(filename);
			sysFiletable.setFileType(imagehz);
			sysFiletable.setCreateId(ShiroUtils.getUserId()+"");
			sysFiletable.setFileUrl(savepath);
			sysFiletable.setCreateTime(new Date());
			sysFiletable.setCreateId(ShiroUtils.getUserId());
			sysFiletable.setCreateName(ShiroUtils.getUserName());
			sysFiletable.setFileRealname(file.getOriginalFilename());

			sysFiletableService.save(sysFiletable);

//			R r = R.ok();
//			r.put("fileId", sysFiletable.getId());
//			r.put("path", savepath);
//			r.put("url", request.getContextPath() + "/fileAction/loadImg?cateogry=" + savepath);
	 
	        String serverPath = new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
	                request.getContextPath()).toString();
	       
	        nm.put("relativeFile", relativeFile);
	        nm.put("id", sysFiletable.getId());
	        
	        return  nm;
	 
	    } catch (Exception e) {
	       // LOGGER.info("error: {}", e);
	    }
	    return nm;
	}
	
}
